package com.ydy.interceptor;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.ydy.model.RequestLog;
import com.ydy.service.requestLog.RequestLogService;
import com.ydy.threadpool.TaskPool;
import com.ydy.threadpool.task.SaveLogTask;
import com.ydy.utils.IpUtil;

/**
 * 日志拦截器 请求链接校验
 * 
 *
 */
@Component
public class RequestLogInterceptor extends HandlerInterceptorAdapter {
	private final static Logger log = LoggerFactory.getLogger(RequestLogInterceptor.class);
	private static ThreadLocal<RequestLog> threadLocal = new ThreadLocal<RequestLog>();

	public static Set<String> urlSet = null;
	static {
		urlSet = new HashSet<String>();
		urlSet.add("/admin/login");
		urlSet.add("/order/create");
		urlSet.add("/good/listSpu");
		urlSet.add("/pay/callback");
		urlSet.add("/pay/checkOutOrder");
	}
	@Autowired
	private RequestLogService requestLogService;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		if (handler instanceof HandlerMethod) {
			String requestUrl = request.getRequestURI();
			String ip = IpUtil.getIp(request);
			log.info("ip: {} -> {}", ip, requestUrl);
			if (urlSet.contains(requestUrl)) {
				RequestLog requestLog = null;
				requestLog = new RequestLog(requestUrl, ip, new Date());
				threadLocal.set(requestLog);
			}
		}
		return true;
	}

	/**
	 * 后处理回调方法，实现处理器的后处理（但在渲染视图之前），此时我们可以通过modelAndView（模型和视图对象）
	 * 对模型数据进行处理或对视图进行处理，modelAndView也可能为null。
	 */
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		RequestLog requestLog = threadLocal.get();
		if (requestLog != null) {
			requestLog.setReqLong(System.currentTimeMillis() - requestLog.getReqTime().getTime());
			TaskPool.execute(new SaveLogTask(requestLog, requestLogService));
			threadLocal.remove();
		}
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}

}
